package com.yonyou.mm.service;

import com.yonyou.mm.connector.ConnectService;
import com.yonyou.mm.entity.ConfigParamVO;
import com.yonyou.mm.util.ConstUtil;
import com.yonyou.mm.util.EnumMethod;
import com.yonyou.mm.params.ParamsEngine;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 配置业务处理类
 * 
 * @date 2017年1月18日 上午8:45:36
 * @author wangjwm
 *
 */
@Service("ConfigUtil")
public class ServiceUtil {

	/**
	 * 判断是否登录成功
	 * 
	 * @param paramData
	 * @return true登录成功；false登录失败
	 */
	public boolean isLogin(HashMap<String, Object> paramData,HttpSession session) {
		String usertype = (String) paramData.get(ConstUtil.USERTYPE);
		String username = (String) paramData.get(ConstUtil.USERNAME);
		String password = (String) paramData.get(ConstUtil.PASSWORD);
		if(usertype.equals("admin")){
			if ((username == "" || username == null) || (password == "" || password == null)) {
				return false;
			} else {
				String username1 = (String) ParamsEngine.getXmlConfig().getProperty("TransferClient.admin");
				String password1 = (String) ParamsEngine.getXmlConfig().getProperty("TransferClient.adminpsd");
				if (username.equals(username1) && password.equals(password1)) {
					return true;
				}
			}
		}else {
			JSONObject result = loginNC(username,password);
			if(result.containsKey("result") && result.getString("result").equals("0")){
				session.setAttribute(ConstUtil.GROUP,result.get(ConstUtil.GROUP));
				return true;
			}
		}
		session.setAttribute(ConstUtil.GROUP,"00017510000000000LNR");

//		return false;
		//测试默认登录成功
		return true;
	}

	/**
	 * 加载系统配置信息
	 * 
	 * @param model
	 * @return
	 */
	public Model addAdminAttr(Model model) {
		StringBuffer sb = new StringBuffer();

		// NC服务地址
		String ncip = ParamsEngine.getXmlConfig().getString("TransferClient.ncip");
		sb.append(new ConfigParamVO("ncip", ncip).toString());

		// NC数据源设置
		String ncdataresource = ParamsEngine.getXmlConfig().getString("TransferClient.ncdataresource");
		sb.append(new ConfigParamVO("ncdataresource", ncdataresource).toString());
		
		// 用户名
		String ncusername = ParamsEngine.getXmlConfig().getString("TransferClient.ncusername");
		sb.append(new ConfigParamVO("ncusername", ncusername).toString());
		
		// 用户密码
		String ncuserpassword = ParamsEngine.getXmlConfig().getString("TransferClient.ncuserpassword");
		sb.append(new ConfigParamVO("ncuserpassword", ncuserpassword).toString());

		// NC版本
		String ncversion = ParamsEngine.getXmlConfig().getString("TransferClient.ncversion");
		sb.append(new ConfigParamVO("ncversion", ncversion).toString());

		String val = "{" + sb.toString().substring(0, sb.toString().length() - 1) + "}";
		model.addAttribute("config", JSONObject.fromObject(val));
		return model;

	}


	/**
	 * 加载车间配置信息
	 *
	 * @return
	 */
	public String addWorkTaskAttr(HashMap<String,Object> attr) {
		StringBuffer sb = new StringBuffer();

		// 用户名
		String ncusername = (String) attr.get("username");
		sb.append(new ConfigParamVO("username", ncusername).toString());

		String val = "{" + sb.toString().substring(0, sb.toString().length() - 1) + "}";

		return val;

	}

	/**
	 * 修改XML配置文件
	 * 
	 * @param obj
	 */
	public void saveConfig(Map<Object, Object> obj) {
		// 读取
		Document document = null;
		String str = this.getClass().getResource("/").getPath();
		str = str.substring(1, str.indexOf("classes"));
		String path = str + ParamsEngine.xmlConfigPath;
		try {
			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			File file = new File(path);
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			document = builder.parse(file);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Iterator<Entry<Object, Object>> ite = obj.entrySet().iterator();
		while (ite.hasNext()) {
			Entry<Object, Object> entry = ite.next();
			String key = (String) entry.getKey();
			String value = (String) entry.getValue();
			document.getElementsByTagName(key).item(0).getFirstChild().setNodeValue(value);
		}
		// 写入
		// 将内存中的Document对象写到xml文件中
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer former;
		try {
			former = tf.newTransformer();
			former.setParameter("version", "1.0");
			former.setParameter("encoding", "UTF-8");
			// 将整个Document对象作为要写入xml文件的数据源
			DOMSource xmlSource = new DOMSource(document);
			// 要写入的目标文件
			StreamResult outputTarget = new StreamResult(new File(path));
			try {
				former.transform(xmlSource, outputTarget);
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		}
		// 重新加载
		try {
			Configuration config = new XMLConfiguration(path);
			if (config != null) {
				ParamsEngine.setXmlConfig(config);
			}
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
	}


	/**
	 * 测试WEB服务器与NC服务器是否连通
	 * 
	 * @return
	 */
	public boolean isLinkNC() {
		// NC用户名
		String ncusername = ParamsEngine.getXmlConfig().getString("TransferClient.ncusername");
		// NC密码
		String ncuserpassword = ParamsEngine.getXmlConfig().getString("TransferClient.ncuserpassword");
		JSONObject result = loginNC(ncusername,ncuserpassword);
		if(result.containsKey("result") && result.getString("result").equals("0")){
			return true;
		}
		return false;
	}

	/**
	 * 测试登录NC结果
	 * @param username
	 * @param pwd
	 * @return
	 */
	public JSONObject loginNC(String username,String pwd){
		// NC服务地址
		String ncip = ParamsEngine.getXmlConfig().getString("TransferClient.ncip")+ ConstUtil.WORKTASK_URL;
		//NC数据源
		String ncDB = ParamsEngine.getXmlConfig().getString("TransferClient.ncdataresource");
		JSONObject data = new JSONObject();

		data.put(ConstUtil.TASKTYPE, "connect");
		data.put(ConstUtil.DBSOURCE, ncDB);
		data.put(ConstUtil.USERNAME, username);
		data.put(ConstUtil.PASSWORD, pwd);

		JSONObject obj = ConnectService.HttpRequest(ncip, EnumMethod.POST.name(), data.toString());
		return obj;
	}


	/**
	 * 填充公共参数并发出后台请求，返回结果
	 * @param info
	 * @param session
	 * @return
	 */
	public static JSONObject requestService(JSONObject info, HttpSession session){
		//数据源名称
		info.put(ConstUtil.DBSOURCE, session.getAttribute(ConstUtil.DBSOURCE));
		//用户、密码
		info.put(ConstUtil.USERNAME, session.getAttribute(ConstUtil.USERNAME));
		info.put(ConstUtil.PASSWORD, session.getAttribute(ConstUtil.PASSWORD));
		info.put(ConstUtil.GROUP,session.getAttribute(ConstUtil.GROUP));
		info.put(ConstUtil.ORG,session.getAttribute(ConstUtil.ORG));

		String docServiceURL = ParamsEngine.getXmlConfig().getString("TransferClient.ncip") + ConstUtil.WORKTASK_URL;
		//请求后台处理
		JSONObject  result = ConnectService.HttpRequest(docServiceURL, EnumMethod.POST.name(), info.toString());
		return  result;
	}

	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

}

